#include <iostream>
#include "consts.h"
#include "AbstractPlayer.cpp"
#include "HumanPlayer.cpp"

using namespace std;

const char BOARD_HEIGHT = 3;
const char BOARD_WIDTH = 3;

const char NUM_PLAYERS = 2;

/*
 * A game of tic-tac-toe for two players.
 */
class TicTacToe {

	private:

		AbstractPlayer ** players; 						// points to the players
		char nextPlayer;								// index of next player to move
		symbols_t board [BOARD_HEIGHT][BOARD_WIDTH];	// game board
	
	public:
	
		TicTacToe (AbstractPlayer**);
		~TicTacToe ();
		bool validMove (move);
		char nextMove ();
		void printBoard();
};

TicTacToe::TicTacToe (AbstractPlayer** pplayers) {
	
	players = pplayers;
	nextPlayer = 0;
	
	for (char i = 0; i < BOARD_HEIGHT; i++) {
		
		for (char j = 0; j < BOARD_WIDTH; j++) {
			
			board[i][j] = empty;
		}
	}
}

TicTacToe::~TicTacToe () {
	
}

bool TicTacToe::validMove (move m) {

	if ((m.x >= 0) &&
		(m.y >= 0) &&
		(m.x < BOARD_WIDTH) && 
		(m.y < BOARD_HEIGHT) && 
		(board[m.y][m.x] == empty)) {
			
			return true;
	}
		
	return false;
}

char TicTacToe::nextMove () {
	
	AbstractPlayer* p = players[nextPlayer];
	
	while (true) {
		
		move m = p -> getMove();
		
		if (validMove(m)) {
			
			board[m.y][m.x] = p -> getSymbol();
			
			nextPlayer = (nextPlayer + 1) % NUM_PLAYERS;
			
			break;
		}
	}
}

void TicTacToe::printBoard () {
	
	for (char i = 0; i < BOARD_HEIGHT; i++) {
		
		cout << "--------" << endl;
		cout << "|";
		
		for (char j = 0; j < BOARD_WIDTH; j++) {
			
			switch (board[i][j]) {
				
				case x: cout << "x|"; break;
				case o: cout << "o|"; break;
				case empty: cout << " |"; break;
			}
		}
		
		cout << endl;
	}
}

int main () {
	
	HumanPlayer marcel (x);
	HumanPlayer franz (o);
	
	AbstractPlayer** players = new AbstractPlayer*[2];
	
	players[0] = &marcel;
	players[1] = &franz;
	
	TicTacToe game (players);
	
	game.printBoard();
	return 0;
}
